<template>
  <div>
    <template v-if="isHasExpand">
      <div class="expand-icon" @click="onChangeExpand">
        <Icon icon="ant-design:caret-right-outlined" v-if="!isExpand" />
        <Icon icon="ant-design:caret-down-outlined" v-if="isExpand" />
      </div>
    </template>

    <div class="attr-item-value">
      <a-select
        v-model:value="dataSourceConfig.dataSourceType"
        :options="dataSourceTypeOptions"
        :showSearch="true"
      />

      <div v-if="dataSourceConfig.dataSourceType === 'function'">
        <div class="sub-title">选择函数</div>
        <a-select
          v-model:value="dataSourceConfig.functionName"
          :options="functionList"
          :showSearch="true"
          optionFilterProp="label"
        />
      </div>

      <div v-if="dataSourceConfig.dataSourceType === 'dataObject'">
        <div class="sub-title">选择数据对象</div>
        <a-select
          v-model:value="dataSourceConfig.dataObjectId"
          :options="dataObjList"
          :showSearch="true"
          optionFilterProp="label"
        />
      </div>

      <div v-if="dataSourceConfig.dataSourceType === 'const'">
        <div class="sub-title">数据源JSON</div>
        <a-textarea v-model:value="dataSourceConfig.constValue" />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, watch } from 'vue'
import { api, useAxiosResponse } from '/@/api'
import {
  BwPageResultOutputSysDataObjectAppGetListOutput,
  BwPageResultOutputSysFunctionAppGetListOutput,
} from '@bitwit/tenantapi'
import { BwDataSourceConfigModel } from './model'
import { DefaultOptionType } from 'ant-design-vue/es/select'

export default defineComponent({
  name: 'BwNodeAttrsConstConfigDataSource',
  props: {
    value: {
      type: [String, Object] as PropType<BwDataSourceConfigModel>,
    },
    /** 是否有展开功能 */
    isHasExpand: {
      type: Boolean,
    },
    isExpand: {
      type: Boolean,
    },
    /** 默认值 */
    defaultValue: {
      type: [String, Number],
    },
  },
  emits: ['update:value', 'change', 'update:isExpand'],
  setup(props, { emit }) {
    const onChangeExpand = () => {
      emit('update:isExpand', !props.isExpand)
    }
    /** 数据源配置 */
    const dataSourceConfig = reactive<BwDataSourceConfigModel>({
      /** 数据源类型 */
      dataSourceType: 'function',
      /** 函数名称  */
      functionName: '',
      /** 数据对象ID */
      dataObjectId: '',
      /** 数据源常量值 */
      constValue: '',
    })

    /** 数据源类型 */
    const dataSourceTypeOptions = [
      {
        label: '函数',
        value: 'function',
      },
      {
        label: '数据对象',
        value: 'dataObject',
      },
      {
        label: '常量',
        value: 'const',
      },
    ]

    /** 函数列表 */
    const functionList = ref<DefaultOptionType[]>([])
    /** 获取函数列表 */
    const getFunctionList = () => {
      return new Promise<void>((resolve, reject) => {
        api
          .apiSysFunctionGetListPost()
          .then((res) => {
            const resData =
              useAxiosResponse<BwPageResultOutputSysFunctionAppGetListOutput>(
                res
              )
            functionList.value =
              resData?.rows?.map((item) => {
                return {
                  label: item.name,
                  value: item.code,
                }
              }) ?? []
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    /** 数据对象列表 */
    const dataObjList = ref<DefaultOptionType[]>([])
    /** 获取数据对象列表 */
    const getDataObjectList = () => {
      return new Promise<void>((resolve, reject) => {
        api
          .apiSysDataObjectGetListPost()
          .then((res) => {
            const resData =
              useAxiosResponse<BwPageResultOutputSysDataObjectAppGetListOutput>(
                res
              )
            dataObjList.value =
              resData?.rows?.map((item) => {
                return {
                  label: item.name,
                  value: item.id,
                }
              }) ?? []
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    }

    watch(
      dataSourceConfig,
      (config) => {
        const dataSourceConfigJSON = JSON.stringify(config)
        if (JSON.stringify(props.value) !== dataSourceConfigJSON) {
          emit('update:value', dataSourceConfigJSON)
        }
      },
      { immediate: true, deep: true }
    )

    watch(
      () => props.value,
      (newVal) => {
        try {
          let newConfig: BwDataSourceConfigModel
          /** 判断是否为对象 */
          if (typeof newVal !== 'object') {
            newConfig = JSON.parse(newVal ?? '')
            return
          } else {
            newConfig = newVal
          }
          dataSourceConfig.dataSourceType =
            newConfig?.dataSourceType ?? 'function'
        } catch (error) {
          console.error(error, '数据源配置报错')
        }
      },
      { immediate: true, deep: true }
    )

    onMounted(() => {
      getFunctionList()
      getDataObjectList()
    })

    return {
      dataSourceConfig,
      dataSourceTypeOptions,
      functionList,
      dataObjList,

      onChangeExpand,
    }
  },
})
</script>

<style lang="less" scoped>
.expand-icon {
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.attr-item-value {
  flex: 1;

  .sub-title {
    padding: 4px 0;
  }
}
.ant-select {
  width: 100%;
}
</style>
